import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getSystemConfigList } from '@/api/system'

export const useAppStore = defineStore('app', () => {
  const systemConfigs = ref({})
  const configsLoaded = ref(false)

  // 加载系统配置
  async function loadSystemConfigs() {
    try {
      const response = await getSystemConfigList()
      if (response && response.data) {
        const configs = response.data.items || response.data || []
        // 将配置转换为key-value对象
        const configMap = {}
        configs.forEach(config => {
          configMap[config.key] = config.value
        })
        systemConfigs.value = configMap
        configsLoaded.value = true
      }
    } catch (error) {
      console.error('加载系统配置失败:', error)
      // 使用默认配置
      systemConfigs.value = {
        siteName: '通用后台管理系统',
        siteDescription: '基于Vue3+.NET Core的现代化后台管理系统',
        adminEmail: 'admin@example.com',
        adminPhone: '13800138000',
        maxLoginAttempts: '5',
        sessionTimeout: '30',
        fileUploadLimit: '10MB',
        systemVersion: 'v1.0.0',
        buildDate: '2025-07-31'
      }
      configsLoaded.value = true
    }
  }

  // 获取配置值
  function getConfig(key, defaultValue = '') {
    return systemConfigs.value[key] || defaultValue
  }

  // 获取系统名称
  function getSystemName() {
    return getConfig('siteName', '通用后台管理系统')
  }

  // 获取系统描述
  function getSystemDescription() {
    return getConfig('siteDescription', '基于Vue3+.NET Core的现代化后台管理系统')
  }

  // 获取系统版本
  function getSystemVersion() {
    return getConfig('systemVersion', 'v1.0.0')
  }

  return {
    systemConfigs,
    configsLoaded,
    loadSystemConfigs,
    getConfig,
    getSystemName,
    getSystemDescription,
    getSystemVersion
  }
})
